let that;
let api = require("../../mars/services/api.js");
let utils = require("../../utils/util.js");
import config from '../../mars/conf/config';

Component({
  pageLifetimes: {
    show() {
      if (typeof this.getTabBar === 'function' &&
        this.getTabBar()) {
        this.getTabBar().setData({
          selected: 3
        });
        that.getPartInEvent();
      }

      let height = wx.getStorageSync('height');
      if (!height) {
        wx.navigateTo({
          url: '/pages/calorieSet/calorieSet',
        });
        return;
      }

      // that.clearInput();
      that.getActivityLastPunch();
    }
  },
  data: {
    isIphoneX: false,
    previewImg: "",
    waist: "",
    weight: "",
    bmi: "",
    description: "",
    id: "",
    punchTextStatus: "打卡",
    is_private: 0,
    liverRate: "",
    activityInfo: {
      id: "",
      event_tag: "",
      name: ""
    }
  },
  methods: {
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
      that = this;
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
      
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {

    },
    chooseImg() {
      wx.chooseImage({
        count: 1, // 默认9
        sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function(res) {
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          var tempFilePaths = res.tempFilePaths;
          var tempFilesSize = res.tempFiles[0].size;
          if (tempFilesSize <= 1000000) {
            that.setData({
              previewImg: tempFilePaths[0]
            });
          } else {
            wx.showToast({
              title: '图片限制1M',
            })
          }
        }
      })
    },
    bindWaistInput(e) {
      let value = e.detail.value;
      that.setData({
        waist: value
      });
    },
    bindWeightInput(e) {
      let value = e.detail.value;
      let height = wx.getStorageSync('height');
      if (!height) {
        that.setData({
          weight: 0,
        });
        wx.navigateTo({
          url: '/pages/calorieSet/calorieSet',
        });
      }
      that.setData({
        weight: value,
        bmi: utils.calcBmi(value, height)
      });
    },
    bindDescInput(e) {
      let value = e.detail.value;
      that.setData({
        description: value
      });
    },
    punch() {
      if (that.data.isLoading) return;
      let punchStatus = that.data.punchTextStatus == '分享' ? true : false;
      if (punchStatus) {
        wx.navigateTo({
          url: '/pages/sharePunchInfo/sharePunchInfo?share=1&id=' + that.data.id,
        });
        return;
      }

      let formData = {
        user_id: wx.getStorageSync('user').id,
        waist: that.data.waist,
        weight: that.data.weight,
        liver_rate: that.data.liverRate,
        bmi: that.data.bmi,
        description: "",
        is_private: that.data.is_private,
        event_tag: that.data.is_event_punch ? that.data.activityInfo.event_tag : ''
      }
      if (formData.waist > 200 || formData.waist <= 0) {
        wx.showToast({
          title: "腰围输入不正确",
          icon: "none"
        })
        return;
      }
      if (formData.weight > 200 || formData.waist <= 0) {
        wx.showToast({
          title: "体重输入不正确",
          icon: "none"
        })
        return;
      }

      if (!formData.waist || !formData.weight || !formData.bmi) {
        wx.showToast({
          title: "请输入体重和腰围",
          icon: "none"
        })
        return;
      }

      wx.showLoading({
        title: '正在加载中...',
      });
      this.setData({
        isLoading: true
      });
      if (that.data.previewImg) {
        wx.uploadFile({
          url: api.savePunchImgInfo.url,
          filePath: that.data.previewImg,
          name: 'file',
          formData: formData,
          header: {
            'content-type': 'multipart/form-data'
          },
          success: function(res) {
            res = JSON.parse(res.data);
            wx.showToast({
              title: '打卡成功',
              icon: 'success',
              duration: 1200
            });

            that.setData({
              isLoading: false,
              punchTextStatus: '分享',
              id: res.data.id
            });
          }
        })
      } else {
        api.WxRequest(api.savePunchInfo, formData, function(res) {
          wx.showToast({
            title: '打卡成功',
            icon: 'success',
            duration: 1200
          });

          that.setData({
            isLoading: false,
            id: res.data.id
          });
          
          setTimeout(() => {
            wx.switchTab({
              url: '/pages/communityIndex/communityIndex',
            });
          }, 1200);
        });
      }
    },
    switchChange(e) {
      let isCheck = e.detail.value;
      this.setData({
        is_private: +isCheck
      });
    },
    switchAcvtityChange(e) {
      let isCheck = e.detail.value;
      this.setData({
        is_event_punch: +isCheck
      });
    },
    getPartInEvent(e) {
      let userId = wx.getStorageSync("user").id;
      that.getUserEventByUserId(userId).then((data) => {
        let eventId = data[0] && data[0].event_id;
        if (eventId) return that.getEventInfoByEventId(eventId);
        throw new Error();
      }).then(data => {
        let activityInfo = data[0];
        if (activityInfo && activityInfo.id) {
          that.setData({
            activityInfo: activityInfo,
            is_event_punch: true,
          });
        }
      }).catch(() => {});
    },
    getUserEventByUserId(userId) {
      return new Promise(function(resolve, reject) {
        api.WxRequest(api.getUserEventByUserId, {
          userId: userId
        }, (res) => {
          resolve(res.data);
        });
      });
    },
    getEventInfoByEventId(eventId) {
      return new Promise(function(resolve, reject) {
        api.WxRequest(api.getEventInfoByEventId, {
          eventId: eventId
        }, (res) => {
          resolve(res.data);
        });
      })
    },
    bindLiverRageInput(e) {
      let value = e.detail.value;
      that.setData({
        liverRate: value
      });
    },
    getActivityLastPunch(e) {
      api.WxRequest(api.getActivityLastPunch, {
        userId: wx.getStorageSync('user').id
      }, (res) => {
        if (res.data.length) {
          that.setData({
            waist: res.data[0].waist,
            bmi: res.data[0].bmi,
            weight: res.data[0].weight,
            liverRate: res.data[0].liver_rate,
          });
        }
      })
    },
    clearInput(){
      that.setData({
        previewImg: "",
        waist: "",
        weight: "",
        bmi: "",
        id: "",
        punchTextStatus: "打卡",
        is_private: 0,
        liverRate: "",
        activityInfo: {
          id: "",
          event_tag: "",
          name: ""
        }
      })
    }
  }
})